#include <hi_types_base.h>
#include <hi_early_debug.h>
#include <hi_stdlib.h>
#include <hi_uart.h>
#include <hi_task.h>
#include <iot_uart.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio_ex.h"
#include "hi_io.h"
#include "iot_gpio.h"
#include "crc32.h"

#define LED_TEST_GPIO 9




unsigned int Crc32_Get( unsigned char *buf, unsigned int len)
{
    unsigned int i, crc = 0xFFFFFFFF;
    for (i = 0; i < len; i++) {
        crc = crc32table[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); /* 8: right move 8 bit */
    }
    return crc ^ 0xFFFFFFFF;
}


hi_u16 Uart_DataPackage(Crc32Type *databuf , hi_u8 *uart_data , hi_u16 len)
{
    hi_u32 crc32_code = 0;

    memcpy_s( uart_data         , 2  , databuf->FrameHeader , 2  );
    memcpy_s(&uart_data[2]      , 2  , &(databuf->MsgLen)   , 2  );
    memcpy_s(&uart_data[4]      , len, databuf->MsgBuf      , len);
    memcpy_s(&uart_data[4 + len], 1  , &(databuf->FrameTail), 1  );
    crc32_code = Crc32_Get(uart_data, (len + 5));
    uart_data[len + 5] = (hi_u8) ((crc32_code & 0xff000000)>>24);
    uart_data[len + 6] = (hi_u8) ((crc32_code & 0x00ff0000)>>16);
    uart_data[len + 7] = (hi_u8) ((crc32_code & 0x0000ff00)>>8);
    uart_data[len + 8] = (hi_u8)   crc32_code;
    return len+9;
}

hi_u8 Check_UartMsg_Crc(hi_u8 *buf, hi_u16 len)
{
    hi_u32 CrcCheck = 0;
    if (len) 
    {
        CrcCheck = Crc32_Get(buf, len);
        //printf("\nlen = %d\nbuf:",len);
        //for(i=0;i<len;i++)    printf(" %X",buf[i]);
        //printf("\n%x %x %x %x",(CrcCheck & 0xff000000)>>24 , ((CrcCheck & 0x00ff0000)>>16) , ((CrcCheck & 0x0000ff00)>>8 ) ,  ((CrcCheck & 0x000000ff) ));
        if (((hi_u8)((CrcCheck & 0xff000000)>>24) != buf[len   ]) && 
            ((hi_u8)((CrcCheck & 0x00ff0000)>>16) != buf[len +1]) && 
            ((hi_u8)((CrcCheck & 0x0000ff00)>>8 ) != buf[len +2]) && 
            ((hi_u8)( CrcCheck                  ) != buf[len +3])) 
        {
            return 0;
        }
    }
    return 1;
}

hi_u8 UartMsg_Receive(Crc32Type *databuf, hi_u8 *uart_data , hi_u16 uart_len)
{    
    hi_u8 len;
    len=uart_len - 4;
    if(Check_UartMsg_Crc(uart_data, len))
    {
        memcpy_s( databuf->FrameHeader , 2    ,  uart_data         , 2    );
        memcpy_s( &(databuf->MsgLen)   , 2    , &uart_data[2]      , 2    );
        memcpy_s( databuf->MsgBuf      , len-5, &uart_data[4]      , len-5);
        memcpy_s( &(databuf->FrameTail), 1    , &uart_data[len -1] , 1    );
        if( (databuf->FrameHeader[0]) == 0xaa   &&
            (databuf->FrameHeader[1]) == 0x55   &&
            (databuf->FrameTail     ) == 0xff   )
            {
                return 1;
            }
    }
    return 0;
}


